#!/usr/bin/env jython
#-*- coding: utf-8 -*-

__author__ = "Sérgio Severino, 9733"
__version__ = "v1.0"


from javax.swing import JFrame, JPanel, JLabel, JComboBox, WindowConstants, SwingConstants, JScrollPane
from javax.swing import JMenuBar, JMenu, JMenuItem, JTextArea, JButton
from java.awt import BorderLayout, GridLayout
from java.lang import System
from jyCode.database import Database
from commonCode.httpServer import HttpServer
from jyCode.htmlFile import HtmlFile



class MyDialog2:
    '''
    A class that starts a dialog with a simple interface
    it does the statistics of
    teachers per degree per establishment per year
    '''
    def __init__(self, data, log):
        self.data = data
        self.log = log
        self.frame = JFrame("Teachers per degree per establishment per year")
        self.frame.setLayout(BorderLayout())

        self.label1 = JLabel('Establishment', SwingConstants.CENTER)
        self.label2 = JLabel('Degree', SwingConstants.CENTER)

        establishmentList = []
        for name in self.data.getDifEstablishmentName():
            establishmentList.append(name.decode('utf-8'))
            pass

        degreeList = []
        for name in self.data.getDifDegree():
            degreeList.append(name.decode('utf-8'))
            pass
        
        self.comboBox1 = JComboBox(establishmentList)
        self.comboBox2 = JComboBox(degreeList)

        
        btn1 = JButton('Save list in CSV',actionPerformed=self.evt_saveCSVList)
        btn2 = JButton('Save stats in CSV',actionPerformed=self.evt_saveCSVStats)
        btn3 = JButton('Cancel',actionPerformed=self.evt_exit)

        cbPanel1 = JPanel()
        cbPanel1.add(self.label1, BorderLayout.NORTH)
        cbPanel1.add(self.comboBox1, BorderLayout.SOUTH)

        cbPanel2 = JPanel()
        cbPanel2.add(self.label2, BorderLayout.NORTH)
        cbPanel2.add(self.comboBox2, BorderLayout.SOUTH)
        
        self.frame.add(cbPanel1, BorderLayout.NORTH)
        self.frame.add(cbPanel2, BorderLayout.CENTER)
    
        bPanel = JPanel(GridLayout(0,3))
        bPanel.add(btn1)
        bPanel.add(btn2)
        bPanel.add(btn3)
        
        self.frame.add(bPanel, BorderLayout.SOUTH)
        
        self.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.frame.pack()
        self.frame.setVisible(True)
        pass

    def evt_exit(self, event):
        self.log.append("Closed teachers per degree per establishment per year window.\n")
        self.frame.dispose()
        pass

    def evt_saveCSVStats(self, event):
        # event that calls a method to save the statistics in a CSV file
        self.log.append("Creating statistics...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox1.getSelectedIndex()]
        degree = self.data.getDifDegree()[self.comboBox2.getSelectedIndex()]
        self.log.append("Saving in CSV...\n")
        self.data.createCSVStatsPerDegreePerEstablishment( degree, establishment )
        self.log.append("Done\n")
        pass
    
    def evt_saveCSVList(self, event):
        # event that calls a method to save the list of teachers in a CSV file
        self.log.append("Creating teachers list...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox1.getSelectedIndex()]
        degree = self.data.getDifDegree()[self.comboBox2.getSelectedIndex()]        
        self.log.append("Saving in CSV...\n")
        self.data.createCSVTListPerDegreePerEstablishment( degree, establishment )
        self.log.append("Done\n")
        pass
    pass


class MyDialog1:
    '''
    A class that starts a dialog with a simple interface
    it does the statistics of
    teachers per categorie per establishment per year
    '''
    def __init__(self, data, log):
        self.data = data
        self.log = log
        self.frame = JFrame("Teachers per categorie per establishment per year")
        self.frame.setLayout(BorderLayout())

        self.label1 = JLabel('Establishment', SwingConstants.CENTER)
        self.label2 = JLabel('Categorie', SwingConstants.CENTER)

        establishmentList = []
        for name in self.data.getDifEstablishmentName():
            establishmentList.append(name.decode('utf-8'))
            pass

        categorieList = []
        for name in self.data.getDifCategories():
            categorieList.append(name.decode('utf-8'))
            pass
        
        self.comboBox1 = JComboBox(establishmentList)
        self.comboBox2 = JComboBox(categorieList)

        
        btn1 = JButton('Save list in CSV',actionPerformed=self.evt_saveCSVList)
        btn2 = JButton('Save stats in CSV',actionPerformed=self.evt_saveCSVStats)
        btn3 = JButton('Cancel',actionPerformed=self.evt_exit)

        cbPanel1 = JPanel()
        cbPanel1.add(self.label1, BorderLayout.NORTH)
        cbPanel1.add(self.comboBox1, BorderLayout.SOUTH)

        cbPanel2 = JPanel()
        cbPanel2.add(self.label2, BorderLayout.NORTH)
        cbPanel2.add(self.comboBox2, BorderLayout.SOUTH)
        
        self.frame.add(cbPanel1, BorderLayout.NORTH)
        self.frame.add(cbPanel2, BorderLayout.CENTER)
    
        bPanel = JPanel(GridLayout(0,3))
        bPanel.add(btn1)
        bPanel.add(btn2)
        bPanel.add(btn3)
        
        self.frame.add(bPanel, BorderLayout.SOUTH)
        
        self.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.frame.pack()
        self.frame.setVisible(True)
        pass

    def evt_exit(self, event):
        self.log.append("Closed teachers per categorie per establishment per year window.\n")
        self.frame.dispose()
        pass

    def evt_saveCSVStats(self, event):
        # event that calls a method to save the statistics in a CSV file
        self.log.append("Creating statistics...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox1.getSelectedIndex()]
        categorie = self.data.getDifCategories()[self.comboBox2.getSelectedIndex()]
        self.log.append("Saving in CSV...\n")
        self.data.createCSVStatsPerCategoriePerEstablishment( categorie, establishment )
        self.log.append("Done\n")
        pass
    
    def evt_saveCSVList(self, event):
        # event that calls a method to save the list of teachers in a CSV file
        self.log.append("Creating teachers list...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox1.getSelectedIndex()]
        categorie = self.data.getDifCategories()[self.comboBox2.getSelectedIndex()]
        self.log.append("Saving in CSV...\n")
        self.data.createCSVTListPerCategoriePerEstablishment( categorie, establishment )
        self.log.append("Done\n")
        pass
    pass


class MyDialog0:
    '''
    A class that starts a dialog with a simple interface
    it does the statistics of
    teachers per establishment per year
    '''
    def __init__(self, data, log):
        self.data = data
        self.log = log
        self.frame = JFrame("Teachers per establishment per year")
        self.frame.setLayout(BorderLayout())

        self.label = JLabel('Establishment', SwingConstants.CENTER)

        establishmentList = []
        for name in self.data.getDifEstablishmentName():
            establishmentList.append(name.decode('utf-8'))
            pass
        
        self.comboBox = JComboBox(establishmentList)

        
        btn1 = JButton('Save list in CSV',actionPerformed=self.evt_saveCSVList)
        btn2 = JButton('Save stats in CSV',actionPerformed=self.evt_saveCSVStats)
        btn3 = JButton('Cancel',actionPerformed=self.evt_exit)

        cbPanel = JPanel()
        cbPanel.add(self.comboBox, BorderLayout.CENTER)
        
        self.frame.add(cbPanel, BorderLayout.CENTER)
    
        bPanel = JPanel(GridLayout(0,3))
        bPanel.add(btn1)
        bPanel.add(btn2)
        bPanel.add(btn3)

        
        self.frame.add(self.label, BorderLayout.NORTH )
        
        self.frame.add(bPanel, BorderLayout.SOUTH)
        
        
        self.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.frame.pack()
        self.frame.setVisible(True)
        pass

    def evt_exit(self, event):
        self.log.append("Closed teachers per degree per establishment per year window.\n")
        self.frame.dispose()
        pass

    def evt_saveCSVStats(self, event):
        # event that calls a method to save the statistics in a CSV file
        self.log.append("Creating statistics...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox.getSelectedIndex()]
        self.log.append("Saving in CSV...\n")
        self.data.createCSVStatsPerEstablishment( establishment )
        self.log.append("Done\n")
        pass
    
    def evt_saveCSVList(self, event):
        # event that calls a method to save the list of teachers in a CSV file
        self.log.append("Creatinh teachers list...\n")
        establishment = self.data.getDifEstablishmentName()[self.comboBox.getSelectedIndex()]
        self.log.append("Saving in CSV...\n")
        self.data.createCSVTListPerEstablishment( establishment )
        self.log.append("Done\n")
        pass
    pass


class MyFrame(JFrame):
    '''
    The class that creates the windows with all the interface
    '''
    def __init__(self):
        super(MyFrame, self).__init__()

        self.initUI()
        pass

    def initUI(self):

        menuBar = JMenuBar()

        menuTmp0 = JMenu ("File")
        menuTmp1 = JMenuItem("Exit", actionPerformed=self.evt_exit)
        menuTmp0.add(menuTmp1)
        menuBar.add(menuTmp0)

        menuTmp0 = JMenu("Database")
        menuTmp1 = JMenuItem("Create and open database", actionPerformed=self.evt_createDB)
        menuTmp0.add(menuTmp1)
        menuTmp1 = JMenuItem("Open database", actionPerformed=self.evt_openDB)
        menuTmp0.add(menuTmp1)
        menuBar.add(menuTmp0)

        menuTmp0 = JMenu("Statistics")
        menuTmp1 = JMenu("Create statistics of")
        menuTmp0.add(menuTmp1)
        menuTmp2 = JMenuItem(" teachers in the higher education system per establishment per year", actionPerformed=self.evt_csvNTpEpY)
        menuTmp1.add(menuTmp2)
        menuTmp2 = JMenuItem(" teachers divided per categories per establisment and per year", actionPerformed=self.evt_csvNTpCpEpY)
        menuTmp1.add(menuTmp2)
        menuTmp2 = JMenuItem(" teachers divided per type of degree per establishment and per year", actionPerformed=self.evt_csvNTpDpEpY)
        menuTmp1.add(menuTmp2)
        menuBar.add(menuTmp0)

        menuTmp0 = JMenu("Html")
        menuTmp1 = JMenu("Create html with list of")
        menuTmp0.add(menuTmp1)
        menuTmp2 = JMenuItem("teachers in the higher education system per establishment per year", actionPerformed=self.evt_htmlTpEpY)
        menuTmp1.add(menuTmp2)
        menuTmp2 = JMenuItem("teachers divided per categories per establisment and per year", actionPerformed=self.evt_htmlTpCpEpY)
        menuTmp1.add(menuTmp2)
        menuTmp2 = JMenuItem("teachers divided per type of degree per establishment and per year", actionPerformed=self.evt_htmlTpDpEpY)
        menuTmp1.add(menuTmp2)
        menuBar.add(menuTmp0)

        menuTmp0 = JMenu("Http")
        menuTmp1 = JMenuItem("Start server", actionPerformed=self.evt_startHttpServer)
        menuTmp0.add(menuTmp1)
        menuBar.add(menuTmp0)

        self.setJMenuBar(menuBar)


        self.title = "TP1 LP Jython"
        self.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        self.size = (500, 400)

        # the log with all the info
        self.log = JTextArea( text = "Log:\n", editable = False )

        self.slog = JScrollPane(self.log)
        self.slog.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
  
        self.add(self.slog)

        self.visible = True

        # the http server port
        self.port = 8000

        pass

    def evt_exit(self, event):
        self.log.append("Shut down.\n")
        System.exit(0)
        pass

    def evt_createDB(self, event):
        # event to convert the files to database
        self.log.append("Creating Database from folder...\n")
        Database.csvFolderToSQliteDB( 'rebcsv', 'data.db' )
        self.log.append("Finished creating Database...\n")
        self.evt_openDB(event)
        pass

    def evt_openDB(self, event):
        # event to create the database object
        self.log.append("Opening Database...\n")
        try:
            self.data = Database( 'data.db' )
            self.log.append("Successfully opened the Database.\n")
        except:
            self.log.append("ERROR: Database not found.\n")
            pass
        pass


    def evt_csvNTpEpY(self, event):
        # event to create the csv file of teachers per establishment per year.
        self.log.append("Processing...\n")
        try:
            MyDialog0( self.data, self.log )
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
        else:
            self.log.append("Done.\n")
            pass
        
        pass

    def evt_csvNTpCpEpY(self, event):
        # event to create the csv file of teachers per categorie per establishment per year
        self.log.append("Processing...\n")
        try:
            MyDialog1( self.data, self.log )
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
        else:
            self.log.append("Done.\n")
            pass
        
        pass

    def evt_csvNTpDpEpY(self, event):
        # event to create the csv file of teachers per degree per establishment per year
        self.log.append("Processing...\n")
        try:
            MyDialog2( self.data, self.log )
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
        else:
            self.log.append("Done.\n")
            pass
        pass

    def evt_htmlTpEpY(self, event): 
        # event to create the html file of teachers per establishment per year
        self.log.append("Generating html file...\n")
        try:
            HtmlFile.createHtmlOfTeachersPerEstablishmentPerYear( self.data )
            self.log.append("Done.\n")
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
            pass
        
        pass

    def evt_htmlTpCpEpY(self, event):
        # event to create the html file of teachers per categorie per establishment per year
        self.log.append("Generating html file...\n")
        try:
            HtmlFile.createHtmlOfTeachersPerCategoriePerEstablishmentPerYear( self.data )
            self.log.append("Done.\n")
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
            pass
        pass

    def evt_htmlTpDpEpY(self, event):
        # event to create the html file of teachers per degree per establishment per year
        self.log.append("Generating html file...\n")
        try:
            HtmlFile.createHtmlOfTeachersPerDegreePerEstablishmentPerYear( self.data )
            self.log.append("Done.\n")
        except:
            self.log.append("ERROR:\nPlease, open the Database first.\n")
            pass
        pass

    def evt_startHttpServer(self, event):
        # the event that starts the http server
        self.log.append("Starting HTTP server on port " + str(self.port) + ".\n")
        try:
            self.httpServ = HttpServer( self.port )
        except:
            self.log.append("HTTP server already running or the port is busy.\nChanging port.\n")
            self.port = self.port + 1
            self.evt_startHttpServer(event)
        else:
            self.log.append("HTTP serving at port: " + str(self.port) +  "\n")
            pass
        pass
    
    pass

if __name__ == '__main__':
    MyFrame()
